import torch
from torch import nn, Tensor
from typing import Tuple
import torch.nn.functional as F
from torch.autograd import Variable

class FocalLoss(nn.Module):
    r"""
        This criterion is a implemenation of Focal Loss, which is proposed in
        Focal Loss for Dense Object Detection.

            Loss(x, class) = - \alpha (1-softmax(x)[class])^gamma \log(softmax(x)[class])

        The losses are averaged across observations for each minibatch.

        Args:
            alpha(1D Tensor, Variable) : the scalar factor for this criterion
            gamma(float, double) : gamma > 0; reduces the relative loss for well-classiﬁed examples (p > .5),
                                   putting more focus on hard, misclassiﬁed examples
            size_average(bool): By default, the losses are averaged over observations for each minibatch.
                                However, if the field size_average is set to False, the losses are
                                instead summed for each minibatch.


    """
    def __init__(self, class_num, alpha=None, gamma=2, size_average=True):
        super(FocalLoss, self).__init__()
        if alpha is None:
            self.alpha = Variable(torch.ones(class_num, 1))
        else:
            if isinstance(alpha, Variable):
                self.alpha = alpha
            else:
                self.alpha = Variable(alpha)
        self.gamma = gamma
        self.class_num = class_num
        self.size_average = size_average
        # self.softmax = torch.nn.Softmax()

    def forward(self, inputs, targets):
        N = inputs.size(0)
        C = inputs.size(1)
        # print(inputs.shape)
        P = F.softmax(inputs, dim=1)
        # P = self.softmax(inputs)

        class_mask = inputs.data.new(N, C).fill_(0)
        class_mask = Variable(class_mask)
        ids = targets.view(-1, 1)
        class_mask.scatter_(1, ids.data, 1.)
        #print(class_mask)


        if inputs.is_cuda and not self.alpha.is_cuda:
            self.alpha = self.alpha.cuda()
        alpha = self.alpha[ids.data.view(-1)]

        probs = (P*class_mask).sum(1).view(-1,1)

        log_p = probs.log()
        #print('probs size= {}'.format(probs.size()))
        #print(probs)

        batch_loss = -alpha*(torch.pow((1-probs), self.gamma))*log_p
        #print('-----bacth_loss------')
        #print(batch_loss)


        if self.size_average:
            loss = batch_loss.mean()
        else:
            loss = batch_loss.sum()
        return loss


# class centerloss(nn.Module):
#     def __init__(self):
#         super(centerloss, self).__init__()
#         self.center = nn.Parameter(10 * torch.randn(10, 2))
#         self.lamda = 0.2
#         self.weight = nn.Parameter(torch.Tensor(2, 10))  # (input,output)
#         nn.init.xavier_uniform_(self.weight)
#
#     def forward(self, feature, label):
#         batch_size = label.size()[0]
#         nCenter = self.center.index_select(dim=0, index=label)
#         distance = feature.dist(nCenter)
#         centerloss = (1 / 2.0 / batch_size) * distance
#         out = feature.mm(self.weight)
#         ceLoss = F.cross_entropy(out, label)
#
#         return out, ceLoss + self.lamda * centerloss



# class CircleLoss(nn.Module):
#     def __init__(self, m: float, gamma: float) -> None:
#         super(CircleLoss, self).__init__()
#         self.m = m
#         self.gamma = gamma
#         self.soft_plus = nn.Softplus()
#
#     def forward(self, sp: Tensor, sn: Tensor) -> Tensor:
#         ap = torch.clamp_min(- sp.detach() + 1 + self.m, min=0.)
#         an = torch.clamp_min(sn.detach() + self.m, min=0.)
#
#         delta_p = 1 - self.m
#         delta_n = self.m
#
#         logit_p = - ap * (sp - delta_p) * self.gamma
#         logit_n = an * (sn - delta_n) * self.gamma
#
#         loss = self.soft_plus(torch.logsumexp(logit_n, dim=0) + torch.logsumexp(logit_p, dim=0))
#
#         return loss
#
#
# def convert_label_to_similarity(normed_feature: Tensor, label: Tensor) -> Tuple[Tensor, Tensor]:
#     similarity_matrix = normed_feature @ normed_feature.transpose(1, 0)
#     label_matrix = label.unsqueeze(1) == label.unsqueeze(0)
#
#     positive_matrix = label_matrix.triu(diagonal=1)
#     negative_matrix = label_matrix.logical_not().triu(diagonal=1)
#
#     similarity_matrix = similarity_matrix.view(-1)
#     positive_matrix = positive_matrix.view(-1)
#     negative_matrix = negative_matrix.view(-1)
#     return similarity_matrix[positive_matrix], similarity_matrix[negative_matrix]




class CircleLoss(nn.Module):
    def __init__(self, m: float, gamma: float) -> None:
        super(CircleLoss, self).__init__()
        self.m = m
        self.gamma = gamma
        self.soft_plus = nn.Softplus()

    def forward(self, sp: Tensor, sn: Tensor) -> Tensor:
        ap = torch.clamp_min(- sp.detach() + 1 + self.m, min=0.)
        an = torch.clamp_min(sn.detach() + self.m, min=0.)

        delta_p = 1 - self.m
        delta_n = self.m

        logit_p = - ap * (sp - delta_p) * self.gamma
        logit_n = an * (sn - delta_n) * self.gamma

        loss = self.soft_plus(torch.logsumexp(logit_n, dim=0) + torch.logsumexp(logit_p, dim=0))

        return loss


def convert_label_to_similarity(normed_feature: Tensor, label: Tensor) -> Tuple[Tensor, Tensor]:
    similarity_matrix = normed_feature @ normed_feature.transpose(1, 0)
    label_matrix = label.unsqueeze(1) == label.unsqueeze(0)

    positive_matrix = label_matrix.triu(diagonal=1)
    negative_matrix = label_matrix.logical_not().triu(diagonal=1)

    similarity_matrix = similarity_matrix.view(-1)
    positive_matrix = positive_matrix.view(-1)
    negative_matrix = negative_matrix.view(-1)
    return similarity_matrix[positive_matrix], similarity_matrix[negative_matrix]